//
//  ChangePasswordViewController.m
//  XRSquare
//
//  Created by 穆相臣 on 2018/9/2.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "ChangePasswordViewController.h"
#import "HomeViewController.h"
#import "SortViewController.h"
#import "GrowViewController.h"
#import "MyViewController.h"
@import CoreLocation;
#define IOS8 [[[UIDevice currentDevice] systemVersion]floatValue]>=8.0

@interface ChangePasswordViewController ()
<CLLocationManagerDelegate>
{
    UITextField * oldpassword;

    UITextField * password1;
    UITextField * password2;
    NSString * province;
    NSString * city;
}
@property(nonatomic,retain)CLLocationManager *locationManager;
@end

@implementation ChangePasswordViewController

//开始定位
-(void)locationStart{
    //判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //设置定位精度
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次（这里的设置为每隔百米)
        if (IOS8) {
            //使用应用程序期间允许访问位置数据
            [self.locationManager requestWhenInUseAuthorization];
        }
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        NSLog(@"%@",@"定位服务当前可能尚未打开，请设置打开！");
        
    }
}
#pragma mark - CoreLocation Delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self.locationManager stopUpdatingLocation];
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count >0)
         {
             
             [[NSUserDefaults
               standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",
                                                nil] forKey:@"AppleLanguages"];
             
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             NSString *currCity = placemark.locality;
             if (!currCity) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 currCity = placemark.administrativeArea;
             }
             
             province = placemark.administrativeArea;
             city = currCity;
             
         } else if (error ==nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error !=nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
         
     }];
    
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
    
}

-(void)tapCancel
{
    [password1 resignFirstResponder];
    [password2 resignFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView * backImage = [[UIImageView alloc]initWithFrame:self.view.bounds];
    backImage.image = [UIImage imageNamed:@"lb"];
    backImage.userInteractionEnabled = YES;
    [self.view addSubview:backImage];
    
    UITapGestureRecognizer * tapCancel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCancel)];
    [backImage addGestureRecognizer:tapCancel];
    
    UIButton * backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 20, 40, 40)];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    UILabel * createAccount = [[UILabel alloc]initWithFrame:CGRectMake(20, 120, ScreenWidth - 40, 30)];
    createAccount.font = [UIFont boldSystemFontOfSize:15];
    createAccount.text = @"修改密码";
    [self.view addSubview:createAccount];
    
    oldpassword = [[UITextField alloc]initWithFrame:CGRectMake(20, 170, ScreenWidth - 40, 30)];
    oldpassword.placeholder = @"请输入旧密码";
    [self.view addSubview:oldpassword];
    
    UIView * line1 = [[UIView alloc]initWithFrame:CGRectMake(20, 200, ScreenWidth - 40, 1)];
    line1.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
    [self.view addSubview:line1];
    
    password1 = [[UITextField alloc]initWithFrame:CGRectMake(20, 250, ScreenWidth - 40, 30)];
    password1.placeholder = @"请输入新密码";
    [self.view addSubview:password1];
    
    UIView * line2 = [[UIView alloc]initWithFrame:CGRectMake(20, 280, ScreenWidth - 40, 1)];
    line2.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
    [self.view addSubview:line2];
    
    password2 = [[UITextField alloc]initWithFrame:CGRectMake(20, 320, ScreenWidth - 40, 30)];
    password2.placeholder = @"请再次输入新密码";
    [self.view addSubview:password2];
    
    UIView * line3 = [[UIView alloc]initWithFrame:CGRectMake(20, 350, ScreenWidth - 40, 1)];
    line3.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
    [self.view addSubview:line3];
    
    UIButton * next = [[UIButton alloc]initWithFrame:CGRectMake(20, 390, ScreenWidth - 40, 30)];
    next.layer.borderColor = [UIColor orangeColor].CGColor;
    next.layer.borderWidth = 1;
    next.layer.cornerRadius = 15;
    [next setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [next setTitle:@"完成" forState:UIControlStateNormal];
    [next addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:next];
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)nextAction
{
    // 判断长度大于8位后再接着判断是否同时包含数字和字符
    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if ([password2.text isEqualToString:password1.text]) {
        if ([password2.text length] >= 6 && [password2.text length] <= 12) {
            if ([pred evaluateWithObject:password2.text]) {
//                [NetRequestCenter changePasswordWithS:@"2" mobile:self.phone password:password2.text captcha:self.token checktype:@"1" result:^(BOOL success, NSDictionary *resultDic) {
//                    if (success) {
//                        [self.navigationController popToRootViewControllerAnimated:YES];
//                    }
//                }];
            }
            else
            {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"密码需要字母数字组合" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *centain = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alert addAction:centain];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
        else
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"密码需要8-16位" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *centain = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:centain];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"两次密码不一致" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *centain = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:centain];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

